package com.example.myx5tbsstatictestdemo

import android.app.Application
import android.content.MutableContextWrapper
import android.util.Log
import com.cnstrong.webview2.utils.FileUtils
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsListener
import com.tencent.smtt.sdk.WebView
import org.greenrobot.eventbus.EventBus

class WebViewApplication : Application() {

    companion object {
        private const val TAG = "tgw x5Application"
    }

    override fun onCreate() {
        super.onCreate()
        loadStaticX5(this)
    }


    private fun loadStaticX5(application: Application) {
        // 在调用TBS初始化、创建WebView之前进行如下配置
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)

        if (QbSdk.canLoadX5(application)) {
            Log.d(
                TAG,
                "x5 canLoadX5 ${WebView(MutableContextWrapper(application)).webViewClientExtension}"
            )
        } else {
            val x5FilePath =
                FileUtils.copyAssetsFiles(application, "x5/45738_x5.apk", FileUtils.X5_FILE)
            QbSdk.reset(application)
            QbSdk.setTbsListener(object : TbsListener {
                override fun onDownloadFinish(i: Int) {}
                override fun onInstallFinish(i: Int) {
                    Log.d(TAG, "x5 canLoadX5 onInstallFinish on")
                    EventBus.getDefault().post(X5CanLoadEvent().also { it.progress = i })
                }

                override fun onDownloadProgress(i: Int) {
                    Log.d(TAG, " x5 onDownloadProgress:$i")
                }
            })
            QbSdk.installLocalTbsCore(application, FileUtils.X5_CORE_CODE, x5FilePath)
        }
    }

}
